package site.luojie;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.I0Itec.zkclient.ZkClient;

import static site.luojie.constant.ZkConfigConstant.CONFIG_PATH;

/**
 * 数据源信息监听
 *
 * @author jie.luo
 * @since 2020-08-18
 */
public class DataSourceLister {

    private ZkClient zkClient;

    public void init() throws Exception {

        boolean exists = zkClient.exists(CONFIG_PATH);
        if (!exists) {
            throw new Exception("配置中心未配置数据源信息");
        }

        // 开启节点监听
        lister();

        String string = zkClient.readData(CONFIG_PATH);
        ObjectMapper objectMapper = new ObjectMapper();
        DataSourceInfo dataSourceInfo = objectMapper.readValue(string, DataSourceInfo.class);
        DruidDataSourceFactory.build(dataSourceInfo, false);
    }


    public void lister() {
        zkClient.subscribeDataChanges(CONFIG_PATH, new DataSourceConfigWater());
    }

    public ZkClient getZkClient() {
        return zkClient;
    }

    public void setZkClient(ZkClient zkClient) {
        this.zkClient = zkClient;
    }
}
